package websocket

import (
	"sync"
	"sync/atomic"
)

type sessionMgr struct {
	sessionMap 	sync.Map 			// session列表
	connFd 		uint64 				// 当前绑定的session id
	processor 	MessageProcessor	// 消息处理器
	MessagePool chan chanMessage	//
}



var (
	_sessionMgr *sessionMgr
)

func init() {
	_sessionMgr = new(sessionMgr)
	_sessionMgr.MessagePool = make(chan chanMessage, 1024)
}

func (sm *sessionMgr) SetProcessor(h MessageProcessor) {
	sm.processor = h
}

func (sm *sessionMgr) GenerateFd() uint64 {
	fd := atomic.AddUint64(&sm.connFd, 1)
	return fd
}

func (sm *sessionMgr) AddSession(sess *Session) {
	sm.sessionMap.Store(sess.Fd, sess)
}

func (sm *sessionMgr) DelSession(fd uint64) {
	sm.sessionMap.Delete(fd)
}

func (sm *sessionMgr) StartMQ() {
	var cm chanMessage
	for {
		select {
		case cm = <-sm.MessagePool:
			o, ok := sm.sessionMap.Load(cm.Fd)
			if !ok {
				LOG.Errorf("receive message but no fd(%d)", cm.Fd)
				continue
			}
			sess := o.(*Session)
			if cm.messageType == chanMessageTypeNetBroken {
				sm.processor.OnNetworkBroken(sess)
				sm.DelSession(cm.Fd)
			} else if cm.messageType == chanMessageTypeNormal {
				sm.processor.OnMessage(sess, cm.Data)
			}
		}
	}
}